<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\lists\room;

use app\adminapi\lists\BaseAdminDataLists;
use app\adminapi\service\DataHandleService;
use app\common\lists\ListsExcelInterface;
use app\common\model\Config;
use app\common\model\room\RoomHospital;
use app\common\model\room\RoomHospitalLog;
use app\common\model\room\RoomHospitalUser;
use app\common\lists\ListsSearchInterface;
use app\common\model\user\User;
use think\Db;

/**
 * 全院用户关联列表
 * Class RoomHospitalUserLists
 * @package app\adminapi\listsroom
 */
class RoomHospitalUserLists extends BaseAdminDataLists implements ListsSearchInterface, ListsExcelInterface {

    protected $export_name = '全院住户-导出';
    protected $export_lists = [];
    protected $export_fields = [];

    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function setSearch(): array {
        return [
//            '=' => ['cid', 'rid', 'status', 'user_id'],
//            'between_time' => ['add_time'],
        ];
    }

    public function queryWhere() {
        $param = $this->request->param();
        $where = [];

        if (!empty($this->adminCid) && $this->adminCid !== 0) {
            $where[] = ['cid', '=', $this->adminCid];
        }

        if (!empty($param['cb_ids'])) {
            if (!empty($param['cb_ids'][0])) {
                $where[] = ['cid', '=', $param['cb_ids'][0]];
            }
            if (!empty($param['cb_ids'][1])) {
                $where[] = ['bid', '=', $param['cb_ids'][1]];
            }
        }

        if (isset($param['user_keyword']) && $param['user_keyword'] != '') {
            $user_ids = User::alias("u")->where([
                ['real_name|mobile', 'like', '%' . $param['user_keyword'] . '%']
            ])->column("id");

            $where[] = ['user_id', 'in', $user_ids];
        }

        if (isset($param['room_keyword']) && $param['room_keyword'] != '') {
            $where[] = ['name|address', 'like', '%' . $param['room_keyword'] . '%'];
        }

        if (isset($param['room_type']) && $param['room_type'] != '') {
            $where[] = ['type', '=', $param['room_type']];
        }

        return $where;
    }

    public function get_query() {
        $this_month = date("Ym");
        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");

        if ($this_month == $search_month) {
            $date_month = date("Y年m月");
            return RoomHospital::field([
                "'" . $date_month . "' as date_time",
                "user_id", "user_name", "user_mobile",
                "GROUP_CONCAT(id) as room_ids", "count(id) as room_count",
                "'0' as is_log", // 用于data_append进行判断
            ])->where($this->queryWhere())->where([
                ["user_id", ">", 0],
            ])->with([
                "campus", "building", "user_all_room", "user",
            ])->group("user_id");
        }

        return RoomHospitalUser::field([
            "*",
            "'1' as is_log", // 用于data_append进行判断
        ])->where($this->queryWhere())->where("log_date", $search_month)->with([
            "campus", "building", "user", // "room", "device"
        ]);
    }

    public function query_append($query, $is_page = 1) {
        if ($is_page == 1) {
            $query = $query->limit($this->limitOffset, $this->limitLength);
        }
        return $query->select()->toArray();
    }

    /**
     * @notes 获取全院用户关联列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function lists(): array {
        $export = $this->request->param("export");
        $is_page = 1;
        if (in_array($export, [1, 2])) {
            $is_page = 2;
        }
        $user_arr = $this->query_append($this->get_query(), $is_page);
        $user_arr = (new RoomHospital())->data_append($user_arr);
        return $user_arr;
    }


    /**
     * @notes 获取全院用户关联数量
     * @return int
     * @author likeadmin
     * @date 2024/02/26 16:32
     */
    public function count(): int {
        return $this->get_query()->count();
    }

    public function print_stat_lists() {
        $Season = new RoomHospitalUserExportSeason();
        $Season->setting("lists_month", 1);
        return ($Season)->lists();
//        return $this->lists();
    }

    public function new_print() {
        $this_month = date("Ym");
        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");
        $year = mb_substr($search_month, 0, 4);
        $month = mb_substr($search_month, 4, 2);
        $m_arr = DataHandleService::getQuarterTime($year, $month);
        $time_text = "2024年" . DataHandleService::getQuarterMonth($month);

        if ($this_month == $search_month) {
            $log_time = date("Y年m月", strtotime($this_month));
        } else {
            $log_time = date("Y年m月", strtotime($search_month));
        }

        $union = [];
        $data = [
            "db" => new \think\Db(),
        ];

        if ($search_month == $search_month) {
            $union[] = RoomHospital::query()->field([
                "sort", "room_department", "user_id", "'0' as use_log",
                "GROUP_CONCAT(id) as room_ids", "count(id) as room_count",
                "'" . $search_month . "' as log_date",
            ])->where($this->queryWhere())->where([
                ["user_id", ">", 0],
            ])->with([
                "userAllRoomDevice",
            ])->group("user_id")->buildSql(); // ->select()->toArray();
        }

        $query = RoomHospitalLog::query()->field([
            "sort", "room_department", "user_id", "'1' as use_log",
            "GROUP_CONCAT(rid) as room_ids", "count(rid) as room_count",
            "log_date",
        ])->where([
            ["user_id", ">", 0],
            ["log_date", "in", $m_arr[$month]],
        ])->with([
            "userAllRoomDevice",
            "userAllRoomDeviceNoLog" => function ($q) {
                $q->where("status", "1");
            },
        ]);
        if (count($union) > 0) {
            $query->unionAll($union);
        }
        $lists = $query->group("user_id")->order([
            $data['db']->raw("field(room_department, '空房') asc"), // 科室排序 * 在最后
            $data['db']->raw("field(room_department, '离退休') asc"), // 科室排序 * 在最后
            $data['db']->raw("field(room_department, '家属') asc"), // 科室排序 * 在最后
            $data['db']->raw('convert(room_department using gbk) asc'), // 先进行科室排序
            "sort asc", // 楼栋排序
        ])->select()->toArray();

        $return_lists = $this->data_handling($lists, ["time_text" => $time_text]);
        return $return_lists;
    }

    public function print_lists() {
//        $lists = $this->new_print();
//        $time_text = "2024年03+04+05月";
        $data = [
            "db" => new \think\Db(),
        ];

        $this_month = date("Ym");
        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");
        if ($this_month == $search_month) {
            $time_text = date("Y年m月", strtotime($this_month));
        } else {
            $time_text = date("Y年m月", strtotime($search_month));
        }

        $lists = RoomHospital::field([
            'cid',
            "room_department", "user_id", "'1' as use_log",
            "GROUP_CONCAT(id) as room_ids", "count(id) as room_count",
            "'" . $search_month . "' as log_date",
        ])->where($this->queryWhere())->where([
            ["user_id", ">", 0],
        ])->with([
            "user", "userAllRoomDevice",
        ])->group("user_id")->order([
            $data['db']->raw("field(room_department, '空房') asc"), // 科室排序 * 在最后
            $data['db']->raw("field(room_department, '离退休') asc"), // 科室排序 * 在最后
            $data['db']->raw("field(room_department, '家属') asc"), // 科室排序 * 在最后
            $data['db']->raw('convert(room_department using gbk) asc'), // 先进行科室排序
            "sort asc", // 楼栋排序
        ])->select()->toArray();

        $return_lists = $this->data_handling($lists, ["time_text" => $time_text]);
        return $return_lists;
    }

    public function data_handling($lists, $other_data = []) {
        $config_data = Config::get_room_all();
        $return_lists = [];

        foreach ($lists as $k => $v) {
            if (empty($v['userAllRoomDevice']) || $v['use_log'] == 0) {
                $v['userAllRoomDevice'] = $v['userAllRoomDeviceNoLog'] ?? [];
            }

            if (count($v['userAllRoomDevice']) <= 0) {
                continue;
            }

            foreach ($v['userAllRoomDevice'] as $kk => $vv) {
                if (count($vv['s_device_stat']) > count($vv['d_device_stat'])) {
                    $more_arr = $vv['s_device_stat'];
                } else {
                    $more_arr = $vv['d_device_stat'];
                }

                // 打印水电设备处理
                foreach ($more_arr as $more_key => $more_val) {
                    if ($more_key == 0) {
                        $lift_fee = $vv['lift_fee'] ?? 0;
                        $second_pressure_fee = $vv['second_pressure_fee'] ?? 0;
                    } else {
                        $lift_fee = 0;
                        $second_pressure_fee = 0;
                    }

                    $return_arr = [
                        "room_name" => $vv['name'], // 房间名
                        "user_name" => $vv['user_name'], // 住户名
                        "user_mobile" => $vv['user_mobile'], // 住户手机号

                        "s_base_number" => 1 * ($vv['s_device_stat'][$more_key]['base_number'] ?? 0), // 水表底数
                        "s_reading" => 1 * ($vv['s_device_stat'][$more_key]['reading'] ?? 0), // 水表读数
                        "s_use_total" => 1 * ($vv['s_device_stat'][$more_key]['use_total'] ?? 0), // 用水量
                        "s_price" => 1 * ($vv['s_device_stat'][$more_key]["price"] ?? $config_data['room_apartment_s_device_price']['value']), // 水单价
                        "s_total_fee" => 1 * ($vv['s_device_stat'][$more_key]['total_fee'] ?? 0), // 水表费用

                        "d_base_number" => 1 * ($vv['d_device_stat'][$more_key]['base_number'] ?? 0), // 电表底数
                        "d_reading" => 1 * ($vv['d_device_stat'][$more_key]['reading'] ?? 0), // 电表读数
                        "d_use_total" => 1 * ($vv['d_device_stat'][$more_key]['use_total'] ?? 0), // 用电量
                        "d_price" => 1 * ($vv['d_device_stat'][$more_key]["price"] ?? $config_data['room_apartment_d_device_price']['value']), // 电单价
                        "d_total_fee" => 1 * ($vv['d_device_stat'][$more_key]['total_fee'] ?? 0), // 电表费用

                        "lift_fee" => 1 * $lift_fee, // 电梯费
                        "second_pressure_fee" => 1 * $second_pressure_fee, // 加压费
                        "time_text" => $other_data['time_text'], // 月份
                        "room_department" => $v['room_department'], // 科室
                    ];

                    $return_key = "{$v['room_department']}+{$vv['name']}+{$vv['user_name']}+{$vv['user_mobile']}+{$more_val['log_id']}";
                    if (!empty($return_lists[$return_key])) {
                        $return_lists[$return_key]['s_reading'] = $return_arr['s_reading'] != 0 ? $return_arr['s_reading'] : $return_lists[$return_key]['s_reading'];
                        $return_lists[$return_key]['s_use_total'] += $return_arr['s_use_total'];
                        $return_lists[$return_key]['s_price'] = ($return_lists[$return_key]['s_price'] + $return_arr['s_price']) / 2;
                        $return_lists[$return_key]['s_total_fee'] += $return_arr['s_total_fee'];

                        $return_lists[$return_key]['d_reading'] = $return_arr['d_reading'] != 0 ? $return_arr['d_reading'] : $return_lists[$return_key]['d_reading'];
                        $return_lists[$return_key]['d_use_total'] += $return_arr['d_use_total'];
                        $return_lists[$return_key]['d_price'] = ($return_lists[$return_key]['d_price'] + $return_arr['d_price']) / 2;
                        $return_lists[$return_key]['d_total_fee'] += $return_arr['d_total_fee'];

                        $return_lists[$return_key]['lift_fee'] += $return_arr['lift_fee'];
                        $return_lists[$return_key]['second_pressure_fee'] += $return_arr['second_pressure_fee'];
                    } else {
                        $return_lists[$return_key] = $return_arr;
                    }
                }
            }
        }

        $return_lists = array_values($return_lists);
        return $return_lists;
    }

    public function setExport($name, $lists, $fields) {
        $this->export_name = $name;
        $this->export_lists = $lists;
        $this->export_fields = $fields;
    }

    /**
     * @notes 导出文件名
     * @return string
     * @author 段誉
     * @date 2022/11/24 16:17
     */
    public function setFileName(): string {
        return $this->export_name;
    }

    /**
     * @notes 导出文件名
     * @return array
     * @author 段誉
     * @date 2022/11/24 16:17
     */
    public function setExcelLists() {
        return $this->export_lists;
    }

    /**
     * @notes 导出字段
     * @return string[]
     * @author 段誉
     * @date 2022/11/24 16:17
     */
    public function setExcelFields(): array {
        return $this->export_fields;
    }

}

